package com.manage.modules.controller;

import cn.hutool.core.util.StrUtil;
import com.manage.common.annotation.Log;
import com.manage.common.constant.UserConstants;
import com.manage.common.core.controller.BaseController;
import com.manage.common.core.domain.AjaxResult;
import com.manage.common.core.domain.entity.SysDept;
import com.manage.common.enums.BusinessType;
import com.manage.common.utils.SecurityUtils;
import com.manage.modules.domain.TBaseArea;
import com.manage.modules.service.ITBaseAreaService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * 区域信息Controller
 *
 * @author xu
 * 2021/8/11 14:53
 */
@Api(value = "区域信息控制器", tags = {"区域信息管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/modules/area")
public class TBaseAreaController extends BaseController {
    @Resource
    private ITBaseAreaService areaService;

    /**
     * 获取区域下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(TBaseArea baseArea) {
        List<TBaseArea> areas = areaService.selectAreaList(baseArea);
        return AjaxResult.success(areaService.buildAreaTreeSelect(areas));
    }

//    /**
//     * 加载对应站点区域列表树
//     */
//    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
//    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
//        List<SysDept> depts = deptService.selectDeptList(new SysDept());
//        AjaxResult ajax = AjaxResult.success();
//        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
//        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
//        return ajax;
//    }


    /**
     * 查询区域列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('modules:area:list')")
    @GetMapping("/list/exclude/{areaId}")
    public AjaxResult excludeChild(@PathVariable(value = "areaId", required = false) Long areaId) {
        List<TBaseArea> areas = areaService.selectAreaList(new TBaseArea());
        Iterator<TBaseArea> it = areas.iterator();
        while (it.hasNext()) {
            TBaseArea d = (TBaseArea) it.next();
            if (d.getAreaId().intValue() == areaId
                    || ArrayUtils.contains(StrUtil.split(d.getAncestors(), ","), areaId + "")) {
                it.remove();
            }
        }
        return AjaxResult.success(areas);
    }

    /**
     * 根据区域编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('modules:area:query')")
    @GetMapping(value = "/{areaId}")
    public AjaxResult getInfo(@PathVariable Long areaId) {
        return AjaxResult.success(areaService.selectAreaById(areaId));
    }

    /**
     * 删除区域
     */
    @PreAuthorize("@ss.hasPermi('modules:area:remove')")
    @Log(title = "区域管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{areaId}")
    public AjaxResult remove(@PathVariable Long areaId) {
        if (areaService.hasChildByAreaId(areaId)) {
            return AjaxResult.error("存在下级区域,不允许删除");
        }
        return toAjax(areaService.deleteAreaById(areaId));
    }

    /**
     * 获取区域列表
     */
    @PreAuthorize("@ss.hasPermi('modules:area:list')")
    @GetMapping("/list")
    public AjaxResult list(TBaseArea baseArea) {
        List<TBaseArea> baseAreaList = areaService.selectAreaList(baseArea);
        return AjaxResult.success(baseAreaList);
    }

    /**
     * 新增区域
     */
    @PreAuthorize("@ss.hasPermi('modules:area:add')")
    @Log(title = "区域管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TBaseArea baseArea) {
        if (UserConstants.NOT_UNIQUE.equals(areaService.checkAreaNameUnique(baseArea))) {
            return AjaxResult.error("新增区域'" + baseArea.getAreaName() + "'失败，区域名称已存在");
        }
        return toAjax(areaService.insertArea(baseArea));
    }

    /**
     * 修改区域
     */
    @PreAuthorize("@ss.hasPermi('modules:area:edit')")
    @Log(title = "区域管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TBaseArea baseArea) {
        if (UserConstants.NOT_UNIQUE.equals(areaService.checkAreaNameUnique(baseArea))) {
            return AjaxResult.error("修改区域'" + baseArea.getAreaName() + "'失败，区域名称已存在");
        } else if (baseArea.getParentId().equals(baseArea.getAreaId())) {
            return AjaxResult.error("修改区域'" + baseArea.getAreaName() + "'失败，上级区域不能是自己");
        } else if (StrUtil.equals(UserConstants.DEPT_DISABLE, baseArea.getAreaState() + "")
                && areaService.selectNormalChildrenAreaById(baseArea.getAreaId()) > 0) {
            return AjaxResult.error("该区域包含未停用的子区域！");
        }
        return toAjax(areaService.updateArea(baseArea));
    }
}
